package com.itheima.bigeventt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bigeventt.pojo.Article;
import com.itheima.bigeventt.pojo.Result;
import com.itheima.bigeventt.service.ArticleService;
import com.itheima.bigeventt.service.UserService;
import com.itheima.bigeventt.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = userService.findByUserName((String) map.get("username")).getId();
        article.setCreateUser(id);
        articleService.save(article);
        return Result.success("添加成功");
    }

    @PutMapping
    public Result update(@RequestBody @Validated Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleService.updateById(article);
        return Result.success("修改成功");
    }

    @GetMapping("/detail")
    public Result detail( Integer id) {
        Article article = articleService.getById(id);
        return Result.success(article);
    }

    @DeleteMapping
    public Result delete(Integer id) {
        articleService.removeById(id);
        return Result.success("删除成功");
    }

    @GetMapping
    public Result<Page> findAll(int pageNum, int pageSize,
                                @RequestParam(required = false) String categoryId,//不必须的参数
                                @RequestParam(required = false) String state ) {
        Page page = new Page(pageNum, pageSize);
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        if(categoryId!=null&&!"".equals(categoryId)){
            queryWrapper.eq(Article::getCategoryId,categoryId);
        }
        if(state!=null&&!"".equals(state)){
            queryWrapper.eq(Article::getState,state);
        }
        articleService.page(page, queryWrapper);
        return Result.success(page);
    }


    @GetMapping("/list")
    public Result<String> list(@RequestHeader(name="Authorization") String token, HttpServletResponse response) {
        return Result.success("所有的文章数据");
    }

}
